package com.ipc.app.service.impl;

import org.apache.commons.lang.StringUtils;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import com.ipc.app.dal.dao.UserDAO;
import com.ipc.app.dal.doObject.UserDO;
import com.ipc.app.model.User;
import com.ipc.app.service.UserService;
import com.ipc.app.util.converter.UserConverter;
import com.ipc.app.util.id.IDGenerator;

public class UserServiceImpl implements UserService {
	private UserDAO userDAO;

	private TransactionTemplate transactionTemplate;

	public String createUser(final User user) {
		transactionTemplate
				.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_REQUIRED);
		String userID = (String) transactionTemplate
				.execute(new TransactionCallback() {
					public Object doInTransaction(TransactionStatus arg0) {
						UserDO userDO = UserConverter.userModelToUserDal(user);
						userDO.setUserId(IDGenerator.idGeneration());
						String userID = userDAO.createUser(userDO);
						return userID;
					}

				});
		return userID;
	}

	public void updateUser(final User user) {
		transactionTemplate
				.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_REQUIRED);
		transactionTemplate.execute(new TransactionCallback() {
			public Object doInTransaction(TransactionStatus arg0) {
				UserDO userDO = UserConverter.userModelToUserDal(user);
				userDAO.updateUser(userDO);
				return null;
			}
		});
	}

	public User getUserByID(String userID) {
		if (StringUtils.isBlank(userID)) {
			return null;
		}
		UserDO userDO = userDAO.getUserByID(userID);
		User user = UserConverter.userDalToModel(userDO);
		return user;
	}

	public User getUserByMobileAndPwd(String mobile, String password) {
		UserDO userDO = userDAO.getUserByMobile(mobile);
		if (null != userDO && userDO.getPassword().equals(password)) {
			User user = UserConverter.userDalToModel(userDO);
			return user;
		}
		return null;
	}

	public void updateLastLoginTime(final String userID) {
		transactionTemplate
				.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_REQUIRED);
		transactionTemplate.execute(new TransactionCallback() {
			public Object doInTransaction(TransactionStatus arg0) {
				userDAO.updateLoginTime(userID);
				return null;
			}
		});
	}

	public User getUserByMobile(String mobile) {
		UserDO userDO = userDAO.getUserByMobile(mobile);
		User user = UserConverter.userDalToModel(userDO);
		return user;
	}

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
		this.transactionTemplate = transactionTemplate;
	}

}
